package com.spring.demo.redis.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
public class RedisLock {
    @Autowired
    private RedisTemplate redisTemplate;
    private ThreadLocal<String> threadLocal = new ThreadLocal<>();

    public Boolean lock(String key, Long time, TimeUnit timeUnit) {

        Boolean lock = false;
        String uuid = UUID.randomUUID().toString();
        threadLocal.set(uuid);
        lock = redisTemplate.opsForValue().setIfAbsent(key, uuid, time, TimeUnit.SECONDS);
        if (!lock) {
            while (true) {
                lock = redisTemplate.opsForValue().setIfAbsent(key, uuid, time, TimeUnit.SECONDS);
                if (lock) {
                    break;
                }
            }
        }
        return lock;
    }

    public void unlock(String key) {
        if (threadLocal.get().equals(redisTemplate.opsForValue().get(key))) {
            redisTemplate.delete(key);
        }
    }
}
